<?php


namespace apps\marriage\core\service;


use apps\marriage\core\logic\FileLogic;
use apps\marriage\core\logic\RegionLogic;
use apps\marriage\core\model\Activity;
use apps\marriage\core\model\MemberProfile;
use apps\marriage\core\model\MemberRechargeRecord;
use think\Exception;
use vm\com\BaseService;

class ActivityService extends BaseService
{
    /**
     * @var RegionLogic
     */
    private $regionLogic;

    protected function init()
    {
        parent::init();
        $this->regionLogic = logic('Region', LOGIC_NAMESPACE);
    }

    /**
     * @return Activity
     */
    protected function getModel()
    {
        return new Activity();
    }

    /**
     * @return BaseService|MemberRechargeRecordService
     */
    protected function getMemberRechargeRecordService()
    {
        return service('MemberRechargeRecord', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|MemberProfileService
     */
    protected function getMemberProfileService()
    {
        return service('MemberProfile', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|ActivityMemberService
     */
    protected function getActivityMemberService()
    {
        return service('ActivityMember', SERVICE_NAMESPACE);
    }

    /**
     * @return BaseService|SiteConfigService
     */
    protected function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    /**
     * @return FileLogic
     */
    private function getFileLogic()
    {
        return logic('File', LOGIC_NAMESPACE);
    }

    public function format($data)
    {
        $data['region'] = '';
        $regions = $this->regionLogic->parents($data['region_id']);
        foreach ($regions as $region) {
            $data['region'] .= $region['region_name'];
        }
        $file = $this->getFileLogic()->file($data['img_id']);
        $data['img_url'] = $file['url'];

        $data['begin_time_str'] = date('Y-m-d H:i:s', $data['begin_time']);
        $data['end_time_str'] = date('Y-m-d H:i:s', $data['end_time']);

        $data['apply_deadline_time_str'] = date('Y-m-d H:i:s', $data['apply_deadline_time']);

        return $data;
    }

    public function apply($id, $userId)
    {
        if($this->getActivityMemberService()->info([
            'user_id' => $userId,
            'activity_id' => $id
        ])) {
            throw new Exception('你已申请过');
        }
        $member = $this->getMemberProfileService()->getByUserId($userId);
        if($member['realname_auth_status'] == 0) {
            throw new Exception('请先完成实名认证');
        }
        if($member['gender'] == 0) {
            throw new Exception('请先填写基本资料');
        }
        $activity = $this->getByPk($id);
        if($activity['status'] != Activity::STATUS_ONLINE) {
            throw new Exception('该活动不能报名');
        }
        if($activity['apply_deadline_time'] < time()) {
            throw new Exception('报名时间已过');
        }
        if($member['gender'] == MemberProfile::GENDER_MALE && $activity['apply_amount_male'] >= $activity['amount_male']) {
            throw new Exception('人数已满');
        } else if($member['gender'] == MemberProfile::GENDER_FEMALE && $activity['apply_amount_female'] >= $activity['amount_female']) {
            throw new Exception('人数已满');
        }
        $charge = 0.00;
        if($member['gender'] == MemberProfile::GENDER_MALE) {
            $charge = $activity['charge_male'];
        } else if($member['gender'] == MemberProfile::GENDER_FEMALE) {
            $charge = $activity['charge_female'];
        }

        if($charge > 0 && !$this->getMemberRechargeRecordService()->info([
            'user_id' => $userId,
            'iid' => $id,
            'iid_type' => MemberRechargeRecord::IID_TYPE_ACTIVITY
        ])) {
            try {
                if($this->getMemberProfileService()->decrease('join_offline_activity_amount', [
                    'user_id' => $userId,
                    'join_offline_activity_amount', ['>', 0]
                ])) {
                    $this->getMemberRechargeRecordService()->create([
                        'user_id' => $userId,
                        'iid' => $id,
                        'iid_type' => MemberRechargeRecord::IID_TYPE_ACTIVITY
                    ]);
                }
            } catch (Exception $e) {
                throw new Exception('请先支付', ERROR_ACTIVITY_APPLY_WAIT_PAY);
            }
        }

        $result = $this->getActivityMemberService()->create([
            'user_id' => $userId,
            'activity_id' => $id
        ]);
        if($result) {
            if($member['gender'] == MemberProfile::GENDER_MALE) {
                $field = 'apply_amount_male';
            } else if($member['gender'] == MemberProfile::GENDER_FEMALE) {
                $field = 'apply_amount_female';
            }
            $this->increase($field, ['id' => $id]);
        } else {
            throw new Exception('申请失败');
        }
    }

    public function getSharePoster($activityId, $fromuid)
    {
        $hash = md5($activityId . $fromuid);
        $path = 'uploads/share_poster/activity/' . $hash{0} . '/' . $hash{1} . '/' . $activityId . '/' . $fromuid . '.jpg';
        $url = request()->scheme() . '://' . request()->host() . '/' . getContextPath() . $path;
        if (is_file(WWW_PATH . $path)) {
            return $url;
        }
        if (!is_dir(dirname(WWW_PATH . $path))) {
            makeDir(dirname(WWW_PATH . $path));
        }
        $tempDir = WWW_PATH . 'uploads/temp/' . date('Ymd') . '/';
        if (!is_dir($tempDir)) {
            makeDir($tempDir);
        }
        $activity = $this->getByPk($activityId);
        if(empty($activity)) {
            throw new Exception('活动不存在');
        }
        $activity = $this->format($activity);

        $fontfile = DOC_PATH . 'data/font/Alibaba-PuHuiTi-Regular.otf';
        $textColor = '123,104,238';

        $texts = [];
        $images = [];

        $fname = grabRemoteFile($activity['img_url'], $tempDir);
        $img = $tempDir . $fname;
        $images[] = [
            'url' => $img,       //图片资源路径
            'left' => 60,
            'top' => 240,
            'stream' => 0,             //图片资源是否是字符串图像流
            'right' => 0,
            'bottom' => 0,
            'width' => 630,
            'height' => 350,
            'opacity' => 100
        ];

        $str = $activity['name'];
        $strRows = rowSubstr($str, 2, 23, false);
        $fontSize = 20;
//        $strPos = imagettfbbox($fontSize, 0, $fontfile, $str);
//        $strLineHeight = $strPos[1] - $strPos[7];
        $texts[] = [
            'text' => implode("\n", $strRows),
            'left' => 60,
            'top' => 640,
            'fontPath' => $fontfile,     //字体文件
            'fontSize' => $fontSize,   //字号
            'fontColor' => '0,0,0',       //字体颜色
            'angle' => 0
        ];

        // 生成二维码
        $mpSite = $this->getSiteConfigService()->getValueByCode('mp_site');
        require_once EXTEND_PATH . 'vm/org/phpqrcode.php';
        $qrUrl = $mpSite . '/activity_detail?id='.$activityId.'&replace=1&fromuid=' . $fromuid;
        $qrFile = $tempDir . 'qrcode/' . time() . '_' . rand_string(6) . '.png';
        if(!is_dir(dirname($qrFile))) {
            makeDir(dirname($qrFile));
        }
        \QRcode::png($qrUrl, $qrFile);
        $images[] = [
            'url' => $qrFile,       //图片资源路径
            'left' => 240,
            'top' => 900,
            'stream' => 0,             //图片资源是否是字符串图像流
            'right' => 0,
            'bottom' => 0,
            'width' => 270,
            'height' => 270,
            'opacity' => 100
        ];

        $config = [
            'image' => $images,
            'text' => $texts,
            'background' => DOC_PATH . 'data/images/share_poster_5.jpg'
        ];
        createPoster($config, WWW_PATH . $path);
        return $url;
    }

    public function getSignInQrCodeImg($activityId)
    {
        // 生成二维码
        $mpSite = $this->getSiteConfigService()->getValueByCode('mp_site');
        require_once EXTEND_PATH . 'vm/org/phpqrcode.php';
        $qrUrl = $mpSite . '/activity_signin?id='.$activityId;
        ob_start();//开启缓冲区
        \QRcode::png($qrUrl, false, 'L', 10, 1);//生成二维码
        $img = ob_get_contents();//获取缓冲区内容
        ob_end_clean();//清除缓冲区内容
        $imgData = 'data:png;base64,' . chunk_split(base64_encode($img));//转base64
        ob_flush();
        return $imgData;
    }
}